import { getuser } from '../../utils/storage'
import { request, wxlogin, request2 } from '../../utils/https'
import { procallback } from '../../utils/index'
import {
  getschoolstudenthomeworkbyid,
  changeschoolstudenthomework,
  changeschoolstudenthomeworkitembank,
  oss
} from '../../utils/interfaces'

export default {
  name: 'Writehomework',
  data () {
    return {
      loading: false,
      images: [],
      homework: {
        ID: '',
        createdAt: '',
        data: {},
        schoolclazzs: '',
        star: '',
        type: '',
        uid: '',
        updatedAt: '',
        schoolstudentid: '',
        schoolhomeworkid: '',
        schoolhomework: {
          schoolhomeworkitembank: []
        }
      },
      getimage: true,
      image: '',
      index: 0,
      answer: {}
    }
  },
  async onLoad (query) {
    this.index = 0
    this.images = []
    this.answer = {}
    this.loading = false
    const { ID } = await getuser('user')
    try {
      let code = await wxlogin()
      const data = await request(getschoolstudenthomeworkbyid, {
        data: {
          schoolstudentid: ID,
          ID: query.ID,
          code
        }
      })
      if (!data.data) {
        data.data = {}
      }
      this.homework = data
      wx.setNavigationBarTitle({
        title: data.schoolhomework.title
      })
    } catch (err) {
      wx.showModal({
        title: '提示',
        content: '服务器请求失败，点击确定重新加载',
        success: res => {
          if (res.confirm) {
            this.start()
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  watch: {
    images (v) {
      if (v.length === 9) {
        this.getimage = false
      }
    }
  },
  computed: {
    textarea: {
      get () {
        return this.data
      },
      set (v) {
        this.list2({target: {value: v}})
      }
    },
    title () {
      return `第${this.index + 1}题`
    },
    itembank () {
      const { index, homework } = this
      return homework.schoolhomework.schoolhomeworkitembank[index] || {}
    },
    schoolhomeworkitembank () {
      return this.homework.schoolhomework.schoolhomeworkitembank
    },
    data () {
      const { answer, itembank } = this
      if (itembank.ID) {
        const { ID, type } = itembank
        if (type === '单选' || type === '解答') {
          return answer[ID] || ''
        }
        return answer[ID] || []
      }
      return ''
    }
  },
  methods: {
    list (e) {
      let {value, id} = e.target
      id = Number(id)
      const { ID } = this.itembank
      const data = this.answer[ID] || []
      data[id] = value
      this.setanswer(data)
    },
    list2 (e) {
      console.log(e)
      const {value} = e.target
      this.setanswer(value)
    },
    setanswer (vo) {
      const { itembank } = this
      const { type, ID } = itembank
      if (type === '多选') {
        const v = this.answer[ID] || {}
        const i = v[vo]
        if (i) {
          delete v[vo]
        } else {
          v[vo] = vo
        }
        this.answer[ID] = v
      } else if (type === '填空') {
        this.answer[ID] = vo
      } else {
        this.answer[ID] = vo
      }
      const data = JSON.parse(JSON.stringify(this.answer))
      this.answer = {}
      this.answer = data
    },
    type (vo) {
      return this.data.indexOf(vo) ? 'info' : ''
    },
    async handleOpen2 () {
      const { ID } = await getuser('user')
      const { title, homework, images, answer, schoolhomeworkitembank } = this
      const l = Object.keys(answer).length
      const n = schoolhomeworkitembank.length
      if (l !== n) {
        wx.showToast({title: '还有没答完的题', icon: 'none'})
        return
      }
      try {
        let code = await wxlogin()
        const { error, data } = await procallback(wx.showModal, {
          title: '提交',
          content: '确定要提交吗'
        })
        if (!error) {
          return
        }
        if (data.cancel) {
          return
        }
        wx.showLoading({
          title: '提交中...',
          mask: true
        })
        this.loading = true
        await request2(changeschoolstudenthomework, {
          data: {
            ID: homework.ID,
            type: '已提交',
            code,
            schoolstudentid: ID,
            data: {
              title,
              images
            }
          }
        })
        for (const v in answer) {
          let code = await wxlogin()
          await request2(changeschoolstudenthomeworkitembank, {
            method: 'GET',
            data: {
              schoolstudentid: ID,
              schoolhomeworkitembankid: v,
              data: {
                answer: answer[v]
              },
              code
            }
          })
        }
        wx.hideLoading()
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 1000
        })
        wx.redirectTo({
          url: `../../pages/Completejob/main?ID=${homework.ID}`
        })
      } catch (err) {
        wx.showModal({
          title: '提示',
          content: '服务器请求失败，点击确定重新加载',
          success: res => {
            if (res.confirm) {
              this.handleOpen2()
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    },
    Takephoto () {
      const { getkey, uploadFile, images } = this
      if (images.length >= 9) {
        return
      }
      wx.chooseImage({
        count: 9 - images.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        async success (res) {
          const tempFilePaths = res.tempFilePaths
          if (tempFilePaths.length === 0) return
          const { OSSAccessKeyId, policy, signature } = await getkey()
          for (let v of tempFilePaths) {
            const hz = v.split('/')
            const name = `vue/student/${hz[hz.length - 1]}`
            await uploadFile(name, v, { OSSAccessKeyId, policy, signature })
          }
        }
      })
    },
    async getkey () {
      let code = await wxlogin()
      return request(oss, {
        data: {
          code
        }
      })
    },
    async uploadFile (name, filePath, {policy, OSSAccessKeyId, signature}) {
      const { images } = this
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com',
          filePath,
          name: 'file',
          formData: {
            // eslint-disable-next-line no-template-curly-in-string
            name: '${fileName}',
            key: name,
            OSSAccessKeyId,
            policy,
            signature
          },
          success (res) {
            const k = `https://cdn.hterobot.com/${name}`
            images.push(k)
            resolve(res)
          },
          fail (err) {
            resolve(err)
          }
        })
      })
    }
  }
}
